#include "uimessageloopimpl.h"

#include <stdio.h>

CUiMessageloopImpl::CUiMessageloopImpl(void)
{
}
CUiMessageloopImpl::~CUiMessageloopImpl(void)
{
}
HRESULT CUiMessageloopImpl::Add(IUIWindow* pBase)
{
    m_pVecMessageLoop.push_back(pBase);
    return S_OK;
}
HRESULT CUiMessageloopImpl::Del(IUIWindow* pBase)
{
    VectorUiWindowItemPtr it = m_pVecMessageLoop.begin();

    for (it = m_pVecMessageLoop.begin(); it != m_pVecMessageLoop.end();) {
        if (pBase == *it) {
            it = m_pVecMessageLoop.erase(it);
        } else {
            ++it;
        }
    }

    return S_OK;
}

#if (TARGET_OS == OS_WIN)

#elif (TARGET_OS == OS_POSIX)

#elif (TARGET_OS == OS_MACH)

#endif

int CUiMessageloopImpl::MessageLoop()
{
    SafePtr<NotifyEvent*> event = new NotifyEvent;

#if (TARGET_OS == OS_WIN)

    MSG msg;
    int bRet;
    while ((bRet = GetMessage(&msg, NULL, 0, 0)) != 0) {
        rc_error_continue(bRet != -1);
        if (!TranslateAccelerator(msg.hwnd, NULL, &msg)) {
            event->lParam = msg.lParam;
            event->wParam = msg.wParam;
            event->Window = msg.hwnd;
            event->message = msg.message;
            event->tm = msg.time;
            event->pt.x = msg.pt.x;
            event->pt.y = msg.pt.y;
            if (!PushMessage(event)) {
                TranslateMessage(&msg);
                DispatchMessage(&msg);
            }
        }
    }
#elif (TARGET_OS == OS_POSIX)
    // g++ -o prog prog-2.cc -L/usr/lib/x86_64-linux-gnu -lX11
    // gcc s.cpp - o output - I /usr/X11R6/include -L/usr/X11R6/lib - lX11

#elif (TARGET_OS == OS_MACH)

#endif

    return S_SUCCESS;
}
int CUiMessageloopImpl::PushMessage(const NotifyEvent* event)
{
    VectorUiWindowItemPtr it = m_pVecMessageLoop.begin();

    for (it = m_pVecMessageLoop.begin(); it != m_pVecMessageLoop.end();) {
        (*it)->TranslateMessage(event);
        it++;
    }

    return S_SUCCESS;
}
